package com.yjj.teaching_platform.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Author: YJJ
 * Description:文件上传工具类
 */
@Slf4j
public class FileUploadUtil {


    public static String imageUpload(MultipartFile file, HttpServletRequest request) {

        String fileSavePath = "D:/images/";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String directory = simpleDateFormat.format(new Date()) + "/";
        File dir = new File(fileSavePath+directory);
        String url = "";
        if(!dir.exists()) {
            dir.mkdir();
        }
        log.info("文件存放位置: {}",fileSavePath+directory);

        //.文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String newFileName = UUID.randomUUID().toString().replace("-","")+suffix;
        File newFile = new File(fileSavePath + directory + newFileName);
        try{

            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
             url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/images/"+directory+newFileName;
            log.info("图片已上传... 访问url "+url);
        }catch (IOException e) {

            e.printStackTrace();
        }
        return url;
    }

    public static String videoUpload(MultipartFile file, HttpServletRequest request) {

        String fileSavePath = "D:/videos/";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String directory = simpleDateFormat.format(new Date()) + "/";
        File dir = new File(fileSavePath+directory);
        String url = "";
        if(!dir.exists()) {
            dir.mkdir();
        }
        log.info("文件存放位置: {}",fileSavePath+directory);

        //.文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String newFileName = UUID.randomUUID().toString().replace("-","")+suffix;
        File newFile = new File(fileSavePath + directory + newFileName);
        try{

            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
            url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/videos/"+directory+newFileName;
            log.info("图片已上传... 访问url "+url);
        }catch (IOException e) {

            e.printStackTrace();
        }
        return url;
    }
}
